﻿using PLCS.Domain.Tasks;
using PLCS.EntityFrameworkCore.EntityFrameworkCore;

namespace PLCS.EntityFrameworkCore.Tasks;

public class HisTaskRepository : EfCoreRepository<PLCSDbContext, HisTask, Guid>, IHisTaskRepository
{
    public HisTaskRepository(IDbContextProvider<PLCSDbContext> dbContextProvider) : base(dbContextProvider)
    {
    }

    public async Task<HisTask?> FindByTaskIdAsync(int taskId)
    {
        return await FindAsync(x => x.TaskId == taskId);
    }

    public async Task<HisTask> GetLastTaskAsync()
    {
        var query = await GetQueryableAsync();
        query = query.OrderByDescending(x => x.TaskId);
        var task = await AsyncExecuter.FirstOrDefaultAsync(query);
        return task;
    }

    public async Task<IEnumerable<HisTask>> GetListByTimeAsync(string? startTime = null, string? endTime = null)
    {
        var dbContext = await GetDbContextAsync();
        var query = dbContext.HisTasks.WhereIf(!string.IsNullOrEmpty(startTime), x => x.FinshedTime > DateTime.Parse(startTime))
             .WhereIf(!string.IsNullOrEmpty(endTime), x => x.FinshedTime < DateTime.Parse(endTime)).OrderByDescending(x => x.TaskId);
        return query.ToList();
    }
}